import { OnListener } from "@/interface";
import { RangeDownload } from "../api/download";

let rangeDownload: RangeDownload | null = null;
let obj: {
    process: number;
    filename: string;
    isFinished: boolean;
    isDownloading: boolean;
    time: number;
    id: number;
    blob: string;
    fromFinish: boolean;
} = {
    process: 0,
    filename: "",
    isFinished: false,
    time: 0,
    id: 0,
    blob: "",
    fromFinish: false,
    isDownloading: false
};
let onLister: OnListener = {
    onFinished(time, blob) {
        obj.time = time;
        obj.isFinished = true;
        obj.blob = blob!;
        obj.fromFinish = true;
        obj.isDownloading = false;
        postMessage(obj);
    },
    onProcess(current, total) {
        obj.process = Math.floor((current / total) * 100);
        obj.isDownloading = true;
        obj.fromFinish = false;
        postMessage(obj);
    },
    onStart(fileName) {
        obj.filename = fileName;
        obj.isDownloading = true;
        obj.fromFinish = false
        postMessage( obj )
    },
    onCanceled(){
        obj.isDownloading = false;
        obj.fromFinish = false
        postMessage( obj )
    }
};

onmessage = async function (event) {
    if (!rangeDownload) {
        let file = JSON.parse(event.data.file)
        obj.id = file.id;
        rangeDownload = new RangeDownload(file, onLister, event.data.authorization);
    }
    if (event.data.stop) {
        rangeDownload.StopDownload()
    } else {
        await rangeDownload.rangeDownLoadApi();
    }
};
